<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" th:href="@{/element-plus/index.css}">
</head>
<body>
<div id="app">
    <el-row justify="center">
        <el-col :xs="22" :lg="6" :span="6">
            <el-tabs type="border-card" class="demo-tabs">
                <el-tab-pane label="用户名注册">
                    <!-- 用户名表单 start -->
                    <el-form
                            :model="user"
                            :rules="formRules"
                            ref="userRegisterForm"
                            label-width="80px"
                    >
                        <el-form-item
                                label="用户名"
                                prop="username"
                        >
                            <el-input v-model="user.username" placeholder="请输入用户名" clearable ></el-input>
                        </el-form-item>
                        <el-form-item
                                label="密码"
                                prop="password"
                        >
                            <el-input v-model="user.password" placeholder="请输入密码" type="password" show-password clearable ></el-input>
                        </el-form-item>
                        <el-form-item
                                label="确认密码"
                                prop="repass"
                        >
                            <el-input v-model="user.repass" placeholder="请输入确认密码"  type="password" show-password clearable ></el-input>
                        </el-form-item>
                        <el-form-item
                                label="验证码"
                                prop="captcha"
                        >
                            <el-input v-model="user.captcha" placeholder="请输入验证码" minlength="5" maxlength="5">
                                <template #append>
                                    <img th:src="@{/captcha}" @click="getCaptcha"/>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="usernameRegister">注册</el-button>
                        </el-form-item>
                    </el-form>
                    <!-- 用户名表单 end -->
                </el-tab-pane>
                <el-tab-pane label="手机号注册">手机号</el-tab-pane>
                <el-tab-pane label="邮箱注册">
                    <!-- 邮箱注册 start-->
                    <el-form
                            :model="user"
                            :rules="formRules"
                            ref="emailRegisterForm"
                            label-width="80px"
                    >
                        <el-form-item
                                label="用户名"
                                prop="email"
                        >
                            <el-input v-model="user.email" placeholder="请输入邮箱" clearable ></el-input>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="emailRegister">注册</el-button>
                        </el-form-item>
                    </el-form>
                    <!-- 邮箱注册 end-->
                </el-tab-pane>
            </el-tabs>
        </el-col>
    </el-row>
</div>

<script th:inline="javascript">
    // 获取上下文路径
    /*<![CDATA[*/
    const ctx = /*[[ @{/} ]]*/ '';
    /*]]>*/
</script>
<script th:src="@{/js/vue.global.js}"></script>
<script th:src="@{/element-plus/index.js}"></script>
<script th:src="@{/element-plus/icon.js}"></script>
<script th:src="@{/js/axios.min.js}"></script>

<script >
  const app = Vue.createApp({
    data(){
      return {
          user: {},
          formRules: {
              username: [
                  {required: true, message: "请输入用户名", trigger: "blur"},
                  {validator: this.usernameRule, trigger: "blur"}
              ],
              password: [
                  {required: true, message: "请输入密码", trigger: "blur"},
                  {validator: this.passwordRule, trigger: "blur"}
              ],
              repass:[
                  {required: true, message: "请输入确认密码", trigger: "blur"},
                  {validator: (rule, value, callback) => {
                          if (value === this.user.password){
                              callback();
                          } else {
                              callback(new Error("两次输入密码不一致"));
                          }
                      }, trigger: "blur"}
              ],
              captcha: [
                  {required: true, message: "请输入验证码", trigger: "blur"},
                  {min: 5, max: 5, message: "验证码长度为5", trigger: "blur"}
              ],
              email:[
                  {required: true, message: "请输入邮箱", trigger: "blur"},
                  {type: "email", message: "邮箱格式不正确", trigger: "blur"}
              ]
          }
      }
    },
      methods:{
            // prop 当前校验字段的 prop， value 值， callback 回调函数
          usernameRule(prop, value, callback){
              let reg = /^(?=.*[a-zA-Z])[a-zA-Z0-9]{5,20}$/;
              if (reg.test(value)){
                  // 判断用户名是否存在
                axios.get(ctx + 'user/username/' + value).then(resp => {
                    const data = resp.data;
                    if (data.code == 200){
                        callback();
                    } else {
                        callback(new Error("用户名已存在"));
                    }
                }).catch((error) => {
                    console.error(error);
                });
              } else {
                  callback(new Error("用户名必须以字母开头，长度在6~20之间，只能包含字母、数字"));
              }
              // callback(new Error("用户名已存在"));
            // callback();
          },
          passwordRule(prop, value, callback) {
              const reg = /^[a-zA-Z][a-zA-Z0-9]{5,19}$/;
              if (reg.test(value)){
                    callback();// 通过
                } else {
                    callback(new Error("密码必须以字母开头，长度在6~20之间，只能包含字母、数字"));
              }
          },
          usernameRegister(){
              // 表单校验
              this.$refs['userRegisterForm'].validate((valid) => {
                  if (valid){
                      console.log(this.user);
                      // 发送注册请求
                      axios.post(ctx + 'register', this.user).then(resp => {
                          console.log(resp);
                          const data = resp.data;
                          if (data.code == 200){
                              this.$message({
                                  message: "注册成功",
                                  type: "success",
                                  onClose(){
                                      window.location.href = ctx + "login";
                                  }
                              })
                          } else {
                              this.$message.error(data.msg);
                          }
                      }).catch((error) => {
                          console.error(error);
                      });
                  } else {
                      return false;
                  }
              });
          },
          getCaptcha(){
              // 重新获取验证码
              event.target.src = ctx + "captcha?" + Math.random();
          },
          emailRegister(){
              // 表单校验
              this.$refs['emailRegisterForm'].validate((valid) => {
                  if (valid){
                      console.log(this.user);
                      // 发送邮件
                      axios.get(ctx + 'sendEmail?email=' + this.user.email).then(resp => {
                          console.log(resp);
                          const data = resp.data;
                          if (data.code == 200){
                              this.$message({
                                  message: "注册成功，请前往邮箱激活",
                                  type: "success",
                                  onClose(){
                                      window.location.href = ctx + "login";
                                  }
                              })
                          } else {
                              this.$message.error(data.msg);
                          }
                      }).catch((error) => {
                          console.error(error);
                      });
                  } else {
                      return false;
                  }
              });
          }

      }
  });

  app.use(ElementPlus);
  // 注册所有 Element 图标
  for (const iconName in ElementPlusIconsVue) {
    app.component(iconName, ElementPlusIconsVue[iconName]);
  }

  const vm = app.mount('#app');
</script>
</body>
</html>